package com.bwie.controller;

import com.alibaba.fastjson.JSON;
import com.bwie.client.NettyTcpClient;
import com.bwie.message.TerminalRegisterMessage;
import com.bwie.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 测试控制器
 */
@RestController
public class NettyController {

    @Autowired
    private NettyTcpClient tcpClient;

    @GetMapping("/send")
    public String sendMessage(@RequestParam String message) {
        try {
            // 如果未连接，则先连接服务器
            if(!tcpClient.isOpen()) {
                tcpClient.connect();
            }

            // 发送多个数据包
            tcpClient.sendMessage(message);
            return "消息发送成功";
        } catch (Exception e) {
            return "消息发送失败: " + e.getMessage();
        }
    }

    @PostMapping("/sendRegister")
    public R sendRegisterMessage(@RequestBody TerminalRegisterMessage message) {
        try {
            // 如果未连接，则先连接服务器
            if(!tcpClient.isOpen()) {
                tcpClient.connect();
            }

            // 发送多个数据包
            tcpClient.sendMessage(JSON.toJSONString(message));
            return R.OK();
        } catch (Exception e) {
            return R.ERROR(500, "消息发送失败: " + e.getMessage());
        }
    }

}

